package com.xuecheng.framework.exception;

import com.google.common.collect.ImmutableMap;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.Response;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.model.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.naming.ldap.ExtendedRequest;

/**
 * 异常捕获类
 */
@ControllerAdvice
@Slf4j
public class ExceptionCatch {
    //

    /**
     * 针对Exception异常抛出未进处理,有一下解决办法
     * 在异常捕获类中配置 HttpMessageNotReadableException 为非法参数异常。
     */
    //使用EXCEPTIONs存放异常类型和错误代码的映射,ImmutableMap的特点就是一旦创建不可改变,并且线程安全
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;
    //使用builder来构建一个异常类型和错误代码的异常
    protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();

    //捕获Exception异常
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResponseResult exception(Exception e) {
        log.error("异常捕获: {}\r\n exception: {}", e.getMessage(), e);
        if (EXCEPTIONS == null)
            EXCEPTIONS = builder.build();
            final ResultCode resultCode = EXCEPTIONS.get(e.getClass());
            final ResponseResult responseResult;
            if(resultCode != null){
                responseResult = new ResponseResult(resultCode);
            }else {
                responseResult = new ResponseResult(CommonCode.SERVER_ERROR);
            }
            return responseResult;

    }

    //捕获自定义异常
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult customException(CustomException e) {
        log.error("自定义异常捕获: {}\r\n exception: {}", e.getMessage(), e);
        ResultCode resultCode = e.getResultCode();
        return new ResponseResult(resultCode);
    }
    static {
        //在这里加入一些基础的异常类型判断
        builder.put(HttpMessageNotReadableException.class,CommonCode.INVALID_PARAM);
    }

}
